<template>
  <!--弹出窗-->
  <modal ref="modal_1"
         :title="title"
         :isCloseConfirm="this.editable"
         :fullscreen="this.fullscreen"
         top="3%"
         width="80%"
         :close-on-click-modal="true"
         @modalOpened="opened"
         @modalClose="closed">

    <avue-form :option="option"
               ref="form"
               v-model="form"
               @submit="onSubmit">
      <template #supplierNo v-if="this.editable">
        <el-autocomplete
                style="width: 100%;"
                v-model="form.supplierNo"
                :fetch-suggestions="querySupplierNo"
                placeholder="请输入加工商账号"
                :trigger-on-focus="false"
                @select="selectSupplierNo"
                :fit-input-width="true"
                :disabled="!!this.form.id"
        ></el-autocomplete>
      </template>
      <template #supplierName v-if="this.editable">
        <el-input v-model="form.supplierName" readonly placeholder="请选择加工商名称" @click="selectSupplierName" :disabled="!!this.form.id"/>
      </template>
      <template #prodItem>
        <prod-item ref="prodItem"  @disabledFiled="disabledFiled"></prod-item>
      </template>
    </avue-form>

    <!--底部按钮块, 默认只有"取消"按钮-->
    <template #footerButton>
      <el-button
              type="primary"
              v-if="(permission.prod_main_add || permission.prod_main_edit) && editable"
              :loading="btnLoading"
              @click="this.$refs.form.submit()"
      >保 存
      </el-button>
      <el-button @click="$refs.modal_1.handleClose()">关闭</el-button>
    </template>
    <select-supplier ref="selectSupplierRef" @success="setSupplier"></select-supplier>
  </modal>
</template>

<script>
    import {getList,  add, update, remove, remoteList} from "@/api/anwise/supplier";
    import {findWorkList} from "@/api/anwise/prod/work_price";
    import {saveProd,getDetail} from "@/api/anwise/prod/prod_main";
    import {mapGetters} from "vuex";
    import {Pattern} from "@/utils/validate.js";
    import {dateFormat} from "@/utils/date.js";
    import prodItem from './prod_item.vue';
    import selectSupplier from './select_supplier.vue';

    export default {
        components: {
            prodItem,
            selectSupplier
        },
        data() {
            return {
                emits: ["success"],
                supplierIdTmp:'',
                editable: false,
                title: "生产单信息",
                isCloseConfirm: false,
                fullscreen: false,
                form: {},
                query: {},
                loading: true,
                btnLoading: false,
              hasItem:false,
                option: {
                    card: true,
                    tabs: true,
                    tabsActive: 1,
                    height: 'auto',
                    calcHeight: 30,
                    labelWidth: 150,
                    menuWidth: 120,
                    submitBtn: false,
                    emptyBtn: false,
                    column: [
                        {
                            label: "加工商账号",
                            prop: "supplierNo",
                            type: "number",
                            precision:0,
                            min:0,
                            max:999999999,
                            controls:false,
                            disabled:true,
                            span:8,
                            rules: [{
                                required: true,
                                message: "请输入加工商账号",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "加工商名称",
                            prop: "supplierName",
                            type: "input",
                            disabled:true,
                            span:8,
                            rules: [{
                                required: true,
                                message: "请输入加工商名称",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "生产单号",
                            prop: "tabNo",
                            type: "input",
                            disabled:true,
                            span:8,
                            placeholder:'保存后自动生成单号',
                            rules: [{
                                required: false,
                                message: "请输入生产单号",
                                trigger: "blur"
                            }],
                        },
                      {
                        label: "操作人员",
                        prop: "createUserName",
                        type: "input",
                        disabled:true,
                        span:8,
                      },
                        // {
                        //     label: "版本",
                        //     prop: "version",
                        //     type: "input",
                        //     disabled:true,
                        //     span:8,
                        //     value:'1',
                        //     rules: [{
                        //         required: false,
                        //         message: "请输入版本",
                        //         trigger: "blur"
                        //     }],
                        // },
                        {
                            label: "排单日期",
                            prop: "tabDate",
                            type: "date",
                            valueFormat: 'YYYY-MM-DD',
                            format:'YYYY-MM-DD',
                            span:8,
                            rules: [{
                                required: false,
                                message: "请输入排单日期",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "审批人",
                            prop: "approver",
                            type: "input",
                            disabled:true,
                        },
                        {
                            label: "审批时间",
                            prop: "approverDate",
                            type: "input",
                            disabled:true,
                        },
                        {
                          label: "操作时间",
                          prop: "createTime",
                          type: "input",
                          disabled:true,
                          span:8,
                        },
                        {
                            label: "备注",
                            prop: "remark",
                            type: "textarea",
                            span: 24,
                            minRows:2,
                        },
                        {
                            label: "统一完成日期",
                            prop: "allOkDate",
                            type: "date",
                            valueFormat: 'YYYY-MM-DD',
                            format:'YYYY-MM-DD',
                            span:12,
                            change:	({column,value})=>{this.changeOkDate(value)},
                        },
                    ],
                    group: [
                        {
                            icon: 'el-icon-house',
                            label: '生产项信息',
                            prop: 'group1',
                            column: [
                                {
                                    label: '',
                                    prop: 'prodItem',
                                    className: 'addPadding',
                                    span: 24,
                                    labelWidth: 0,
                                    formslot: true,
                                    display: true,
                                },
                            ],
                        },
                    ]
                },
                data: []
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.prod_main_add, false),
                    viewBtn: this.validData(this.permission.prod_main_view, false),
                    delBtn: this.validData(this.permission.prod_main_delete, false),
                    editBtn: this.validData(this.permission.prod_main_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        mounted() {
          // init()
        },
        methods: {
            changeOkDate(value) {
                let orderItem = this.$refs.prodItem.$refs.tableRef.getTableData().fullData;
                if (orderItem.length > 0) {
                    orderItem.forEach(item => {
                        item.planOkDate = value;
                    })
                }
            },
            // init() {
            //   this.form.tabDate = dateFormat(new Date(),'yyyy-MM-dd');
            // },
          disabledFiled(hasItem) {
            this.hasItem = hasItem;
          },
            selectSupplierName() {
                // if (this.supplierIdTmp) {
                //     this.$confirm("确定将选择数据删除?", {
                //         confirmButtonText: "确定",
                //         cancelButtonText: "取消",
                //         type: "warning"
                //     })
                //         .then(() => {
                //
                //         })
                // }
              this.$refs.selectSupplierRef.showSelect();
            },
            setSupplier(row) {
                this.form.supplierId = row.id;
                this.supplierIdTmp = row.id;
                this.form.deptId = row.deptId;
                this.$refs.prodItem.supplierId = row.id;
                this.form.supplierNo = row.supNo;
                this.form.supplierName = row.supName;
                console.log("row",row);
                findWorkList({supId: row.id, isActive:'是', isAssign:'已审核'}).then(res => {
                    this.$refs.prodItem.genPrice(res.data.data);
                })
            },
            querySupplierNo(val,cb) {
                const reg = Pattern.number;
              this.form.supplierName = "";
                console.log(reg.test(val));
                if (!reg.test(val)) {
                    this.$message({
                        type: "error",
                        message: "加工商账号只能为数字!"
                    });
                    return;
                }

                remoteList(val,1).then(res => {
                    if (res.data.success) {
                        let customerList = [];
                        res.data.data.forEach(item => {
                            customerList.push({
                                value:item.supNo +" - "+item.supName,
                                supId: item.id,
                                deptId: item.deptId,
                                supNo: item.supNo,
                                supName: item.supName,
                            });
                        })
                        cb(customerList);
                    }
                })
            },
            selectSupplierNo(item) {
                console.log(item);
                this.form.supplierId = item.supId;
                this.supplierIdTmp = item.id;
                this.$refs.prodItem.supplierId = item.supId;
                this.form.deptId = item.deptId;
                this.form.supplierNo = item.supNo;
                this.form.supplierName = item.supName;
                findWorkList({supId: item.supId, isActive:'是', isAssign:'已审核'}).then(res => {
                    this.$refs.prodItem.genPrice(res.data.data);
                })
            },
            async validItemEvent() {
                const $table = this.$refs.prodItem.$refs.tableRef
                let errMap = undefined;
                await $table.validate().then((err) => {
                    console.log("err",err);
                    errMap=err;
                })
                return errMap;
            },
            async onSubmit(form, done) {
                const $table = this.$refs.prodItem.$refs.tableRef
                let checkprodItem = false;
                const errMap = await this.validItemEvent();

                if (errMap) {
                    this.$message({
                        type: 'error',
                        message: '生产项信息有误！',
                    });
                    checkprodItem = true;
                    done();
                    return;
                }

                console.log("checkprodItem",checkprodItem);
                if (!checkprodItem) {
                    this.btnLoading = true;
                    // form.isConfirm = this.editable ? 1 : 0;
                    form.addList = $table.getInsertRecords();
                    form.updateList = $table.getUpdateRecords();
                    form.deleteList = $table.getRemoveRecords();
                    form.itemList = $table.getTableData().fullData;
                    if (!form.itemList || form.itemList.length < 1) {
                        this.$message({
                            type: 'error',
                            message: '无生产项信息！',
                        });
                        this.btnLoading = false;
                        done();
                        return;
                    }
                    console.log(form)
                    saveProd(form).then(res => {
                        if (res.data.success) {
                            this.$message({
                                type: "success",
                                message: res.msg || "保存成功!"
                            });
                            setTimeout(() => {
                              this.btnLoading = false;
                              done();
                              this.$refs.modal_1.hide();
                            }, 1000)
                        } else {
                            this.$message({
                                type: "error",
                                message: res.msg || "保存失败!"
                            });
                        }
                    }).catch(err => {
                        console.log(err)
                        done();
                        this.btnLoading = false;
                    })

                }
            },
            show(option) {
                if (option.id) {
                    setTimeout(() => {
                        getDetail(option.id).then(res =>{
                            if (res.data.success) {
                                this.form = res.data.data;
                                this.$refs.prodItem.setData(this.editable, this.form.tabNo, this.form.supplierId)
                                if (res.data.data.supplierId) {
                                    findWorkList({
                                        supId: res.data.data.supplierId,
                                        isActive: '是',
                                        isAssign: '已审核'
                                    }).then(res => {
                                        this.$refs.prodItem.workPrice = res.data.data;
                                    })
                                }
                                if (res.data.data.prodStatus =='已审核') {
                                    this.findObject(this.option.column, 'approver').display = true;
                                    this.findObject(this.option.column, 'approverDate').display = true;
                                } else {
                                    this.findObject(this.option.column, 'approver').display = false;
                                    this.findObject(this.option.column, 'approverDate').display = false;
                                }
                            }
                        })
                    }, 500);
                } else {
                    this.form={}
                    this.form.tabDate = dateFormat(new Date(),"yyyy-MM-dd")
                    this.findObject(this.option.column, 'approver').display = false;
                    this.findObject(this.option.column, 'approverDate').display = false;
                  this.hasItem=false;
                }
                this.title = option.title;
                this.type = option.type;
                this.option.detail = this.type === "view";
                this.editable = this.type !== "view";
                this.$refs.modal_1.show();
                setTimeout(() =>{
                  this.$refs.prodItem.tabDate = this.form.tabDate;
                },1000)
            },
            rowSave(row, done, loading) {
                add(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    loading();
                    window.console.log(error);
                });
            },
            rowUpdate(row, index, done, loading) {
                update(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    loading();
                    window.console.log(error);
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            handleDelete() {
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(this.ids);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.$refs.crud.toggleSelection();
                    });
            },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage){
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize;
            },
            refreshChange() {
                this.onLoad(this.page, this.query);
            },
            onLoad(page, params = {}) {
                this.loading = true;
                getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                    const data = res.data.data;
                    this.page.total = data.total;
                    this.data = data.records;
                    this.loading = false;
                    this.selectionClear();
                });
            },
            opened() {
                console.log("opened")
            },
            closed() {
                this.$emit("success");
            }
        }
    };
</script>

<style>
</style>
